#!/bin/sh

zhelp() {
	script=${0##*/} ; echo "
Usage:

       $script -x|-c <initrd.gz/xz>
          -x: extract
          -c: compress"
	exit
}

#find out compression type...
function compr_func() {
	case "$1" in
		*.gz) UNCOMPREXE=gunzip ; EXT=gz ; COMPREXE=gzip ;;
		*.xz) UNCOMPREXE=unxz   ; EXT=xz ; COMPREXE='xz --check=crc32 --lzma2' ;;
		*) echo "Unsupported compression/format for initrd." ; exit 1 ;;
	esac
}

#args: <extract|compress> <initrd.gz/xz>
function initrd_proc() { 

	OPTION=$1
	shift
	INFILE="$@"
	[ -f "$INFILE" ] || { echo "ERROR: file does not exist: $INFILE"; exit 1; }

	FILE_NAME=`basename "$INFILE"`
	DIR=`dirname "$INFILE"`
	[ "$DIR" = "." ] && DIR=$(pwd)
	INFILE=${DIR}/${FILE_NAME}
	CURDIRX=$DIR

	DIR=/tmp
	cd $DIR
	ln -sf $INFILE ${FILE_NAME}
	[ -f initrd.gz -o -f initrd.xz ] || { echo "initrd.gz/xz not found in $DIR" ; exit 1 ; }

	## now proceed
	compr_func ${FILE_NAME} || { echo "ERROR getting compression type for ${FILE_NAME}" >&2 ; return 1 ; }
	if [ "$OPTION" = "extract" ] ; then
		echo "Expanding at $DIR"
		[ "initrd.${EXT}" != "${FILE_NAME}" ] && cp -f "${FILE_NAME}" initrd.${EXT}
		#-f and -k are options in gunzip, and unxz
		zout="$(${UNCOMPREXE} -f initrd.${EXT} 2>&1)"
		if [ $? -ne 0 ] ; then
			echo -e "${comp}\n${zout}" >&2
			rm -f initrd.${EXT}
			return 5 #error extracting
		fi
		mkdir -p initrd-expanded
		cd initrd-expanded
		cat ../initrd | cpio -i -d -m 2>/dev/null
		rm -f ../initrd
		cd ..
		[ "initrd.${EXT}" != "${FILE_NAME}" ] && rm -f initrd.${EXT}
		rm -f ${HOME}/${FILE_NAME}
		return 0
	else #compress
		echo "Creating $FILE_NAME from $DIR"
		[ -d initrd-expanded ] || { echo "'initrd-expanded' not found in $DIR" ; exit 1 ; }
		cd initrd-expanded
		find . | cpio -o -H newc > ../initrd
		cd ..
		${COMPREXE} -f initrd
		[ "initrd.${EXT}" != "${FILE_NAME}" ] && mv -f initrd.${EXT} "${FILE_NAME}"
		mv -fv ${FILE_NAME} "$CURDIRX"
		return 0
	fi

}

#================================================

case $1 in
	-x) shift ; initrd_proc extract "$@" ; exit $? ;;
	-c) shift ; initrd_proc compress "$@" ; exit $? ;;
esac

zhelp

### END ###
